<?php 
namespace plugins\logistics\model;
use think\Model;
use plugins\store\Common;

/**
 * 评论模型
 */
class LogisticsKdniaoModel extends Model
{
    /**
     * 初始化
     */
   
    private  $EBusinessID = "";
    private  $AppKey = '';//(此Key仅限测试环境使用)
    private  $ReqURL = 'http://api.kdniao.com/Ebusiness/EbusinessOrderHandle.aspx';//即时查询地址

//---------------------------------------------


    /**
     * 即时查询API
     * @param  array $EXinfo    快递鸟配置
     * @param  array $orderInfo 物流信息 
     * @return url响应返回的html
     */
    public function getOrderTracesByJson($ShipperCode,$LogisticCode,$EXinfo,$CustomerName)
    {
        
        $requestData= "{'OrderCode':'','CustomerName':'".$CustomerName."','ShipperCode':'".$ShipperCode."','LogisticCode':'".$LogisticCode."'}";
        $datas = array(
            'EBusinessID' => $EXinfo['EBusinessID'],
            'RequestType' => '8003',
            'RequestData' => urlencode($requestData) ,
            'DataType' => '2',
        );
        $datas['DataSign'] = $this->encrypt($requestData, $EXinfo['AppKey']);
        $result=$this->sendPost($this->ReqURL, $datas);	
        //根据公司业务处理返回的信息......
        
        return $result;
    }


    /**
     * Json方式 调用电子面单接口
     */
    function submitEOrder($requestData,$EXinfo){
        $datas = array(
            'EBusinessID' => $EXinfo['EBusinessID'],
            'RequestType' => '1007',
            'RequestData' => urlencode($requestData) ,
            'DataType' => '2',
        );
        $datas['DataSign'] = $this->encrypt($requestData, $EXinfo['AppKey']);
        $ReqURL = 'http://api.kdniao.com/api/EOrderService';
        $result=$this->sendPost($ReqURL, $datas);	

        //根据公司业务处理返回的信息......
        return $result;
    }


    /**
     * 组装POST表单用于调用快递鸟批量打印接口页面
     */
    function build_form($request_data,$EXinfo) {
        //OrderCode:需要打印的订单号，和调用快递鸟电子面单的订单号一致，PortName：本地打印机名称，请参考使用手册设置打印机名称。支持多打印机同时打印。
        // $request_data = '[{"OrderCode":"order_5f2cf0334f64d","PortName":"XP460B"},{"OrderCode":"order_5f2cf0334f64c","PortName":"XP460B"}]';
 
        $request_data_encode = urlencode($request_data);
    // 如果报数据验证失败 请检查此处get_ip()返回的IP 是否与调用打印的【客户机】IP一致 可以写死IP尝试
        
        $client_ip = request()->ip(0, true);

        $data_sign = $this->encrypt($client_ip.$request_data, $EXinfo['AppKey']);
        
        //是否预览，0-不预览 1-预览
        $is_priview = '1';
        //批量打印接口地址
        $API_URL = 'http://www.kdniao.com/External/PrintOrder.aspx';
        //组装表单
        
        $form = '<form id="form1" method="POST" action="'.$API_URL.'">
        <input type="text" name="RequestData" value="'.$request_data_encode.'"/>
        <input type="text" name="EBusinessID" value="'.$EXinfo['EBusinessID'].'"/>
        <input type="text" name="DataSign" value="'.$data_sign.'"/>
        <input type="text" name="IsPriview" value="'.$is_priview.'"/>
        </form><script>form1.submit();</script>';
        echo $form;
        
        // return $form;

    }



    /**
     *  post提交数据 
     * @param  string $url 请求Url
     * @param  array $datas 提交的数据 
     * @return url响应返回的html
     */
    function sendPost($url, $datas) {
        $temps = array();	
        foreach ($datas as $key => $value) {
            $temps[] = sprintf('%s=%s', $key, $value);		
        }	
        $post_data = implode('&', $temps);
        $url_info = parse_url($url);
        if(empty($url_info['port']))
        {
            $url_info['port']=80;	
        }
        $httpheader = "POST " . $url_info['path'] . " HTTP/1.0\r\n";
        $httpheader.= "Host:" . $url_info['host'] . "\r\n";
        $httpheader.= "Content-Type:application/x-www-form-urlencoded\r\n";
        $httpheader.= "x-forwarded-for:".'60.162.155.29'."\r\n";
        $httpheader.= "Content-Length:" . strlen($post_data) . "\r\n";
        $httpheader.= "Connection:close\r\n\r\n";
        $httpheader.= $post_data;
        $fd = fsockopen($url_info['host'], $url_info['port']);
        fwrite($fd, $httpheader);
        $gets = "";
        $headerFlag = true;
        while (!feof($fd)) {
            if (($header = @fgets($fd)) && ($header == "\r\n" || $header == "\n")) {
                break;
            }
        }
        while (!feof($fd)) {
            $gets.= fread($fd, 128);
        }
        fclose($fd);  
        
        return $gets;
    }

    /**
     * 电商Sign签名生成
     * @param data 内容   
     * @param appkey Appkey
     * @return DataSign签名
     */
    function encrypt($data, $appkey) {
        return urlencode(base64_encode(md5($data.$appkey)));
    }


    /************************************************************** 
     * 
     *  使用特定function对数组中所有元素做处理 
     *  @param  string  &$array     要处理的字符串 
     *  @param  string  $function   要执行的函数 
     *  @return boolean $apply_to_keys_also     是否也应用到key上 
     *  @access public 
     * 
     *************************************************************/  
    function arrayRecursive(&$array, $function, $apply_to_keys_also = false)  
    {  
        static $recursive_counter = 0;  
        if (++$recursive_counter > 1000) {  
            die('possible deep recursion attack');  
        }  
        foreach ($array as $key => $value) {  
            if (is_array($value)) {  
                arrayRecursive($array[$key], $function, $apply_to_keys_also);  
            } else {  
                $array[$key] = $function($value);  
            }  
    
            if ($apply_to_keys_also && is_string($key)) {  
                $new_key = $function($key);  
                if ($new_key != $key) {  
                    $array[$new_key] = $array[$key];  
                    unset($array[$key]);  
                }  
            }  
        }  
        $recursive_counter--;  
    }  


    /************************************************************** 
     * 
     *  将数组转换为JSON字符串（兼容中文） 
     *  @param  array   $array      要转换的数组 
     *  @return string      转换得到的json字符串 
     *  @access public 
     * 
     *************************************************************/  
    function JSON($array) {  
        arrayRecursive($array, 'urlencode', true);  
        $json = json_encode($array);  
        return urldecode($json);  
    }  


}